package com.xxx.blog.service.impl;


import com.github.pagehelper.PageHelper;
import com.xxx.blog.domain.Article;
import com.xxx.blog.mapper.ArticleMapper;
import com.xxx.blog.query.ArticleQuery;
import com.xxx.blog.service.IArticleService;
import com.xxx.blog.dto.ArticleTimeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Article> findAll() {
        List<Article> list = articleMapper.findAll();
        return list;
    }

    @Override
    public Article findOne(Long id) {
        return articleMapper.findOne(id);
    }

    @Override
    public List<Article> findByPage(ArticleQuery articleQuery) {
        PageHelper.startPage(articleQuery.getCurrentPage(), articleQuery.getPageSize());
        return articleMapper.findByPage(articleQuery);
    }

    @Override
    public void updateById(Article article) {
        article.setUpdateTime(new Date());
        articleMapper.updateById(article);
    }

    @Override
    public void insert(Article article) {
        try {
            articleMapper.insert(article);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void deleteById(Long id) {
        articleMapper.deleteById(id);
    }

    @Override
    public void bathArticles(Long[] ids) {
        articleMapper.bathArticles(ids);
    }

    @Override
    public List<ArticleTimeDTO> articleTimeSta() {
        List<ArticleTimeDTO> list = articleMapper.articleTimeSta();
        return list;
    }

    @Override
    public List<Article> getRA(Long id) {
        List<Article> list = articleMapper.getRA(id);
        return list;
    }

    @Override
    public List<Article> getArticlesByTypeID(Long id) {
        List<Article> list = articleMapper.getArticlesByTypeID(id);
        return list;
    }

    //判断是否有时间参数获取相应文章集合,time为all则为查询所有年份的文章
    @Override
    public List<ArticleTimeDTO> articleTimeStaByTime(String time) {
        time = "all".equalsIgnoreCase(time) ? "" : time;
        List<Article> list = articleMapper.articleTimeStaByTime(time);

        //根据年份进行分组：百度看例子
        //String保存的是年份，List<BlogArticle>保存当前年份的集合
        Map<String, List<Article>> resultMap = list.stream().filter(item -> item.getYear() != null).collect(Collectors.groupingBy(Article::getYear));

        List<ArticleTimeDTO> result = new ArrayList<>();

        //遍历resultMap，封装结果进行返回
        for (String year : resultMap.keySet()) {
            ArticleTimeDTO dto = new ArticleTimeDTO();
            dto.setYear(year);
            dto.setArticleList(resultMap.get(year));
            result.add(dto);
        }

        return result;
    }

}
